#include "HttpServer.h"
#include "UserController.h"
#include "SystemController.h"
#include "ConfigController.h"
#include "AlarmController.h"
#include "FileController.h"
#include "ModelController.h"
#include "SceneController.h"
#include "RecordController.h"
#include "DeviceController.h"
#include "../log/SysLog.h"

HttpServer::HttpServer()
{
	// 初始化oatpp 环境
	oatpp::base::Environment::init();
}

HttpServer::~HttpServer()
{
	// 销毁oatpp环境
	oatpp::base::Environment::destroy();
}

void HttpServer::Start(int port)
{
	// 配置路由
	auto router = oatpp::web::server::HttpRouter::createShared();
	// 添加静态目录
	router->route("GET", "/web/*", std::make_shared<WebFileHandler>());
	// 添加路由处理器
	router->route("GET", "/hello", std::make_shared<HelloHandler>());

	// 序列化对象
	auto serializeConfig = oatpp::parser::json::mapping::Serializer::Config::createShared();
	auto deserializeConfig = oatpp::parser::json::mapping::Deserializer::Config::createShared();
	serializeConfig->useBeautifier = true;
	auto objectMapper = oatpp::parser::json::mapping::ObjectMapper::createShared(serializeConfig, deserializeConfig);

	// 文件控制器
	router->addController(std::make_shared<FileController>(objectMapper));
	// 用户控制器
	router->addController(std::make_shared<UserController>(objectMapper));
	// 系统控制器
	router->addController(std::make_shared<SystemController>(objectMapper));
	// 配置控制器
	router->addController(std::make_shared<ConfigController>(objectMapper));
	// 报警控制器
	router->addController(std::make_shared<AlarmController>(objectMapper));
	// 模型控制器
	router->addController(std::make_shared<ModelController>(objectMapper));
	// 场景控制器
	router->addController(std::make_shared<SceneController>(objectMapper));
	// 录像控制器
	router->addController(std::make_shared<RecordController>(objectMapper));
	// 设备控制器
	router->addController(std::make_shared<DeviceController>(objectMapper));

	// 创建 HTTP 连接处理程序
	auto connectionHandler = oatpp::web::server::HttpConnectionHandler::createShared(router);
	// 创建 TCP 连接提供者
	auto connectionProvider = oatpp::network::tcp::server::ConnectionProvider::createShared({ "0.0.0.0", (v_uint16)port, oatpp::network::Address::IP_4 });
	// 打印服务器端口
	LOG_INFO("start http server on port {}", port);

	// 创建服务器
	m_server = std::make_shared<oatpp::network::Server>(connectionProvider, connectionHandler);
	// 运行服务器
	m_thread = std::thread(std::bind(&HttpServer::_Work, this));
}

void HttpServer::Stop()
{
	if (m_server)
	{
		m_server->stop();
		m_server.reset();
		m_server = nullptr;
	}
	if (m_thread.joinable())
	{
		m_thread.join();
	}
}

void HttpServer::_Work()
{
	if (m_server)
	{
		m_server->run();
	}
}
